package imageDemo;

import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

// 可写入的图片
public class WritableImageDemo extends Application {
	private HBox root = new HBox(30);
	private ImageView iv1;
	private ImageView iv2;
	
	public static void main(String[] args) {
		launch(args);
	}
	
	@Override
	public void start(Stage stage) throws Exception {
		
		// 完全自己写入像素的图片
		WritableImage wi1 = new WritableImage(200, 200);		// 写入图片的宽高
		
		PixelWriter pw1 = wi1.getPixelWriter();		// 写像素类
		for(int i=0; i<200; i++) {
			for(int j=0; j<50; j++) {
				pw1.setColor(i, j, Color.RED);
			}
		}
		
		for(int i=0; i<200; i++) {
			for(int j=50; j<100; j++) {
				pw1.setColor(i, j, Color.YELLOW);
			}
		}
		
		for(int i=0; i<200; i++) {
			for(int j=100; j<150; j++) {
				pw1.setColor(i, j, Color.GREEN);
			}
		}
		
		for(int i=0; i<200; i++) {
			for(int j=150; j<200; j++) {
				pw1.setColor(i, j, Color.valueOf("#87CEFF"));
			}
		}
		
		iv1 = new ImageView(wi1);
		// image生成图片文件
		BufferedImage bi = SwingFXUtils.fromFXImage(wi1, null);
		ImageIO.write(bi, "png", new File("C:/Users/ASUS/Desktop/1.png"));	// png为32位(包含透明度),而jpg为24位
		
		// 在图片基础上写入
		Image image = new Image("image/1.jpg");
		WritableImage wi2 = new WritableImage(image.getPixelReader(), 0, 200, 320, 180);	// 从(0,200)开始读取宽320，高180
		
		PixelWriter pi2 = wi2.getPixelWriter();
		for(int i=0; i<100; i++) {
			for(int j=0; j<100; j++) {
				pi2.setColor(i, j, Color.CORNFLOWERBLUE);
			}
		}
		
		iv2 = new ImageView(wi2);
		root.getChildren().addAll(iv1, iv2);
		
		Scene scene = new Scene(root);
		stage.setScene(scene);
		stage.show();
	}
}
